# 10进制
a1 = 11010
# 0b表示2进制
a2 = 0b11010
# 0x表示16进制
a3 = 0x11010


def 十进制转二进制(val):
    str1 = ''
    while val >= 1:
        if val % 2 == 0:
            str1 += '0'
        else:
            str1 += '1'
        val = val // 2
        # print(val)
    return '0b' + str1[::-1]


def 二进制转十进制(val):
    str1 = str(val)
    if str1.startswith('0b') or str1.startswith('0B'):
        str1 = str1[2:]
    temp = 0
    for index, x in enumerate(str1):
        if x == '0':
            continue
        temp = temp + pow(2, len(str1) - 1 - index)
    return temp


def 二进制转十六进制(val):
    str1 = str(val)
    # 如果需要转化的字符串不能被4整除，就在字符串的前面添加0直到满足条件
    while len(str1) % 4 != 0:
        str1 = '0' + str1
    result = ''
    for x in range(0, len(str1), 4):
        temp = str1[x:x + 4]
        # print(temp)
        t1 = 0
        for index, y in enumerate(temp):
            if y == '0':
                continue
            t1 = t1 + pow(2, len(temp) - 1 - index)
        if t1 == 10:
            t1 = 'a'
        elif t1 == 11:
            t1 = 'b'
        elif t1 == 12:
            t1 = 'c'
        elif t1 == 13:
            t1 = 'd'
        elif t1 == 14:
            t1 = 'e'
        elif t1 == 15:
            t1 = 'f'
        result = result + str(t1)
    return '0x' + result


def 十六进制转二进制(val):
    str1 = str(val)
    if str1.startswith('0x') or str1.startswith('0X'):
        str1 = str1[2:]
    result = ''
    for x in str1:
        if x == 'a':
            x = 10
        elif x == 'b':
            x = 11
        elif x == 'c':
            x = 12
        elif x == 'd':
            x = 13
        elif x == 'e':
            x = 14
        elif x == 'f':
            x = 15
        result = result + 十进制转二进制(int(x)).replace('0b', '')
    return result


def 十进制转十六进制(val):
    result = ''
    while val >= 1:
        temp = val % 16
        if temp == 10:
            temp = 'a'
        elif temp == 11:
            temp = 'b'
        elif temp == 12:
            temp = 'c'
        elif temp == 13:
            temp = 'd'
        elif temp == 14:
            temp = 'e'
        elif temp == 15:
            temp = 'f'
        result = result + str(temp)
        val = val // 16
    return '0x' + result[::-1]


def 十六进制转十进制(val):
    str1 = str(val)
    if str1.startswith('0x') or str1.startswith('0X'):
        str1 = str1[2:]
    result = 0
    for index, x in enumerate(str1):
        if x == 'a':
            x = 10
        elif x == 'b':
            x = 11
        elif x == 'c':
            x = 12
        elif x == 'd':
            x = 13
        elif x == 'e':
            x = 14
        elif x == 'f':
            x = 15
        result = result + int(x) * pow(16, (len(str1) - 1 - index))
    return result

# print(十六进制转十进制('2927b'))
# print(十进制转十六进制(100))
# print(十六进制转二进制('0x7db'))
# print(二进制转十六进制('11111011011'))
# print(hex(int('11111011011', 2)))
